<template>
  <div class="file-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <el-icon><FolderOpened /></el-icon>
          文件管理
        </h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>文件管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button 
            type="primary" 
            @click="showUploadDialog"
            v-if="authStore.hasPermission(PERMISSIONS.FILE_UPLOAD)"
          >
            <el-icon><Upload /></el-icon>
            上传文件
          </el-button>
          <el-button @click="refreshFiles">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button 
            @click="createFolder"
            v-if="authStore.hasPermission(PERMISSIONS.FILE_MANAGE)"
          >
            <el-icon><FolderAdd /></el-icon>
            新建文件夹
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalFiles }}</div>
            <div class="stat-label">总文件数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon size">
            <el-icon><DataBoard /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ formatFileSize(stats.totalSize) }}</div>
            <div class="stat-label">总存储空间</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon today">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.todayUploads }}</div>
            <div class="stat-label">今日上传</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon folders">
            <el-icon><Folder /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalFolders }}</div>
            <div class="stat-label">文件夹数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 文件路径导航 -->
    <el-card class="path-card">
      <div class="file-path">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item 
            v-for="(path, index) in currentPath" 
            :key="index"
            @click="navigateToPath(index)"
            class="path-item"
          >
            <el-icon v-if="index === 0"><House /></el-icon>
            <span>{{ path.name }}</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <!-- 筛选工具栏 -->
    <el-card class="filter-card">
      <div class="filter-toolbar">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文件名"
            clearable
            @input="handleSearch"
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="typeFilter"
            placeholder="文件类型"
            clearable
            @change="handleFilter"
            style="width: 120px; margin-left: 12px;"
          >
            <el-option label="全部类型" value="" />
            <el-option label="图片" value="image" />
            <el-option label="文档" value="document" />
            <el-option label="视频" value="video" />
            <el-option label="音频" value="audio" />
            <el-option label="压缩包" value="archive" />
            <el-option label="其他" value="other" />
          </el-select>
          
          <el-select
            v-model="sizeFilter"
            placeholder="文件大小"
            clearable
            @change="handleFilter"
            style="width: 120px; margin-left: 12px;"
          >
            <el-option label="全部大小" value="" />
            <el-option label="小于1MB" value="small" />
            <el-option label="1-10MB" value="medium" />
            <el-option label="10-100MB" value="large" />
            <el-option label="大于100MB" value="xlarge" />
          </el-select>
          
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleFilter"
            style="width: 240px; margin-left: 12px;"
          />
        </div>
        
        <div class="filter-right">
          <el-button @click="resetFilters">重置筛选</el-button>
          <el-button type="primary" @click="applyFilters">应用筛选</el-button>
        </div>
      </div>
    </el-card>

    <!-- 文件列表 -->
    <el-card class="file-list-card">
      <template #header>
        <div class="card-header">
          <span>文件列表</span>
          <div class="header-actions">
            <el-button-group>
              <el-button 
                :type="viewMode === 'list' ? 'primary' : ''"
                @click="viewMode = 'list'"
              >
                <el-icon><List /></el-icon>
                列表视图
              </el-button>
              <el-button 
                :type="viewMode === 'grid' ? 'primary' : ''"
                @click="viewMode = 'grid'"
              >
                <el-icon><Grid /></el-icon>
                网格视图
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 列表视图 -->
      <el-table
        v-if="viewMode === 'list'"
        :data="paginatedFiles"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="文件名" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="file-name">
              <el-icon class="file-icon" :class="getFileIconClass(row.type)">
                <component :is="getFileIcon(row.type)" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ translateFileType(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="uploader" label="上传者" width="120" />
        <el-table-column prop="createdAt" label="上传时间" width="160" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="showPreviewFile(row)">
                预览
              </el-button>
              <el-button size="small" @click="downloadFile(row)">
                下载
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteFile(row)"
                v-if="authStore.hasPermission(PERMISSIONS.FILE_DELETE)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 网格视图 -->
      <div v-else class="grid-view">
        <div 
          v-for="file in paginatedFiles" 
          :key="file.id"
          class="file-card"
          @click="selectFile(file)"
          @dblclick="openFile(file)"
        >
          <div class="file-icon-large">
            <el-icon :class="getFileIconClass(file.type)">
              <component :is="getFileIcon(file.type)" />
            </el-icon>
          </div>
          <div class="file-info">
            <div class="file-name" :title="file.name">{{ file.name }}</div>
            <div class="file-meta">
              <span class="file-size">{{ formatFileSize(file.size) }}</span>
              <span class="file-date">{{ formatDate(file.createdAt) }}</span>
            </div>
          </div>
          <div class="file-actions">
            <el-button-group>
              <el-button size="small" @click.stop="showPreviewFile(file)">
                预览
              </el-button>
              <el-button size="small" @click.stop="downloadFile(file)">
                下载
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click.stop="deleteFile(file)"
                v-if="authStore.hasPermission(PERMISSIONS.FILE_DELETE)"
              >
                删除
              </el-button>
            </el-button-group>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="filteredFiles.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量操作工具栏 -->
    <el-card v-if="selectedFiles.length > 0" class="batch-actions-card">
      <div class="batch-actions">
        <span class="selected-count">已选择 {{ selectedFiles.length }} 个文件</span>
        <el-button-group>
          <el-button @click="batchDownload">
            <el-icon><Download /></el-icon>
            批量下载
          </el-button>
          <el-button 
            @click="batchDelete"
            type="danger"
            v-if="authStore.hasPermission(PERMISSIONS.FILE_DELETE)"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button 
            @click="batchMove"
            v-if="authStore.hasPermission(PERMISSIONS.FILE_MANAGE)"
          >
            <el-icon><FolderOpened /></el-icon>
            批量移动
          </el-button>
        </el-button-group>
      </div>
    </el-card>

    <!-- 文件上传对话框 -->
    <el-dialog
      v-model="uploadDialog.visible"
      title="上传文件"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :file-list="fileList"
        :auto-upload="false"
        :multiple="true"
        :on-change="handleFileChange"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        drag
        class="upload-dragger"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持多文件上传，单个文件大小不超过100MB
          </div>
        </template>
      </el-upload>
      
      <div v-if="fileList.length > 0" class="upload-list">
        <div 
          v-for="(file, index) in fileList" 
          :key="index"
          class="upload-item"
        >
          <div class="file-info">
            <el-icon class="file-icon">
              <component :is="getFileIcon(file.raw?.type)" />
            </el-icon>
            <span class="file-name">{{ file.name }}</span>
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
          </div>
          <div class="upload-progress">
            <el-progress 
              :percentage="file.percentage || 0" 
              :status="file.status === 'success' ? 'success' : file.status === 'exception' ? 'exception' : ''"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="uploadDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="uploading" @click="startUpload">
          开始上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialog.visible"
      title="文件预览"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="previewFile" class="file-preview">
        <!-- 图片预览 -->
        <div v-if="isImage(previewFile.type)" class="image-preview">
          <img :src="previewFile.url" :alt="previewFile.name" />
        </div>
        
        <!-- 文档预览 -->
        <div v-else-if="isDocument(previewFile.type)" class="document-preview">
          <iframe :src="previewFile.url" width="100%" height="600px"></iframe>
        </div>
        
        <!-- 视频预览 -->
        <div v-else-if="isVideo(previewFile.type)" class="video-preview">
          <video :src="previewFile.url" controls width="100%" height="400px"></video>
        </div>
        
        <!-- 音频预览 -->
        <div v-else-if="isAudio(previewFile.type)" class="audio-preview">
          <audio :src="previewFile.url" controls style="width: 100%;"></audio>
        </div>
        
        <!-- 其他文件类型 -->
        <div v-else class="other-preview">
          <div class="preview-icon">
            <el-icon :class="getFileIconClass(previewFile.type)">
              <component :is="getFileIcon(previewFile.type)" />
            </el-icon>
          </div>
          <div class="preview-info">
            <h3>{{ previewFile.name }}</h3>
            <p>文件大小: {{ formatFileSize(previewFile.size) }}</p>
            <p>文件类型: {{ translateFileType(previewFile.type) }}</p>
            <p>上传时间: {{ formatDateTime(previewFile.createdAt) }}</p>
          </div>
          <div class="preview-actions">
            <el-button type="primary" @click="downloadFile(previewFile)">
              <el-icon><Download /></el-icon>
              下载文件
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="downloadFile(previewFile)">
          下载文件
        </el-button>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog
      v-model="folderDialog.visible"
      title="新建文件夹"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="folderFormRef"
        :model="folderForm"
        :rules="folderRules"
        label-width="80px"
      >
        <el-form-item label="文件夹名" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="folderForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入文件夹描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="folderDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="creatingFolder" @click="createFolderConfirm">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import { useAuthStore, PERMISSIONS } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  FolderOpened, Upload, Refresh, FolderAdd, Document, DataBoard, Calendar, Folder,
  House, Search, List, Grid, Download, Delete, UploadFilled, Picture, VideoPlay, Headset, Box
} from '@element-plus/icons-vue'

export default {
  name: 'FileManagement',
  components: {
    FolderOpened, Upload, Refresh, FolderAdd, Document, DataBoard, Calendar, Folder,
    House, Search, List, Grid, Download, Delete, UploadFilled, Picture, VideoPlay, Headset, Box
  },
  setup() {
    const authStore = useAuthStore()

    // 响应式数据
    const loading = ref(false)
    const searchKeyword = ref('')
    const typeFilter = ref('')
    const sizeFilter = ref('')
    const dateRange = ref([])
    const viewMode = ref('list')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const selectedFiles = ref([])
    const uploading = ref(false)
    const creatingFolder = ref(false)

    // 对话框状态
    const uploadDialog = ref({ visible: false })
    const previewDialog = ref({ visible: false })
    const folderDialog = ref({ visible: false })

    // 文件列表和路径
    const files = ref([])
    const currentPath = ref([{ name: '根目录', path: '/' }])

    // 表单数据
    const folderForm = reactive({
      name: '',
      description: ''
    })

    const previewFile = ref(null)
    const fileList = ref([])

    // 表单验证规则
    const folderRules = {
      name: [
        { required: true, message: '请输入文件夹名称', trigger: 'blur' }
      ]
    }

    // 模拟数据
    const mockFiles = [
      {
        id: 1,
        name: '项目文档.pdf',
        size: 2048576,
        type: 'document',
        uploader: '管理员',
        createdAt: new Date().toISOString(),
        url: '/files/project-doc.pdf',
        path: '/documents'
      },
      {
        id: 2,
        name: '系统截图.png',
        size: 1024000,
        type: 'image',
        uploader: '客服小王',
        createdAt: new Date(Date.now() - 3600000).toISOString(),
        url: '/files/screenshot.png',
        path: '/images'
      },
      {
        id: 3,
        name: '培训视频.mp4',
        size: 52428800,
        type: 'video',
        uploader: '管理员',
        createdAt: new Date(Date.now() - 7200000).toISOString(),
        url: '/files/training.mp4',
        path: '/videos'
      }
    ]

    // 计算属性
    const stats = computed(() => ({
      totalFiles: files.value.length,
      totalSize: files.value.reduce((sum, file) => sum + file.size, 0),
      todayUploads: files.value.filter(file => {
        const today = new Date().toDateString()
        return new Date(file.createdAt).toDateString() === today
      }).length,
      totalFolders: 5 // 模拟文件夹数量
    }))

    const filteredFiles = computed(() => {
      let result = files.value

      // 搜索筛选
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(file => 
          file.name.toLowerCase().includes(keyword)
        )
      }

      // 类型筛选
      if (typeFilter.value) {
        result = result.filter(file => file.type === typeFilter.value)
      }

      // 大小筛选
      if (sizeFilter.value) {
        result = result.filter(file => {
          const size = file.size
          switch (sizeFilter.value) {
            case 'small': return size < 1024 * 1024
            case 'medium': return size >= 1024 * 1024 && size < 10 * 1024 * 1024
            case 'large': return size >= 10 * 1024 * 1024 && size < 100 * 1024 * 1024
            case 'xlarge': return size >= 100 * 1024 * 1024
            default: return true
          }
        })
      }

      // 日期筛选
      if (dateRange.value && dateRange.value.length === 2) {
        const [startDate, endDate] = dateRange.value
        result = result.filter(file => {
          const fileDate = new Date(file.createdAt)
          return fileDate >= startDate && fileDate <= endDate
        })
      }

      return result
    })

    const paginatedFiles = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredFiles.value.slice(start, end)
    })

    // 上传相关
    const uploadAction = computed(() => '/api/files/upload')
    const uploadHeaders = computed(() => ({
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    }))
    const uploadData = computed(() => ({
      path: currentPath.value[currentPath.value.length - 1].path
    }))

    // 方法
    const refreshFiles = async () => {
      loading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        files.value = [...mockFiles]
        ElMessage.success('文件列表已刷新')
      } catch (error) {
        ElMessage.error('刷新失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleFilter = () => {
      currentPage.value = 1
    }

    const resetFilters = () => {
      searchKeyword.value = ''
      typeFilter.value = ''
      sizeFilter.value = ''
      dateRange.value = []
      currentPage.value = 1
    }

    const applyFilters = () => {
      currentPage.value = 1
    }

    const handleSelectionChange = (selection) => {
      selectedFiles.value = selection
    }

    const handleSortChange = ({ prop, order }) => {
      console.log('Sort:', prop, order)
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
    }

    const showUploadDialog = () => {
      uploadDialog.value.visible = true
      fileList.value = []
    }

    const handleFileChange = (file, fileList) => {
      console.log('File changed:', file, fileList)
    }

    const handleUploadSuccess = (response, file) => {
      console.log('Upload success:', response, file)
      ElMessage.success(`${file.name} 上传成功`)
    }

    const handleUploadError = (error, file) => {
      console.error('Upload error:', error, file)
      ElMessage.error(`${file.name} 上传失败`)
    }

    const startUpload = () => {
      uploading.value = true
      // 模拟上传过程
      setTimeout(() => {
        uploading.value = false
        uploadDialog.value.visible = false
        ElMessage.success('文件上传完成')
        refreshFiles()
      }, 2000)
    }

    const showPreviewFile = (file) => {
      previewFile.value = file
      previewDialog.value.visible = true
    }

    const downloadFile = (file) => {
      // 模拟下载
      const link = document.createElement('a')
      link.href = file.url
      link.download = file.name
      link.click()
      ElMessage.success(`${file.name} 开始下载`)
    }

    const deleteFile = async (file) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除文件"${file.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const index = files.value.findIndex(f => f.id === file.id)
        if (index !== -1) {
          files.value.splice(index, 1)
        }
        
        ElMessage.success('文件删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    }

    const createFolder = () => {
      folderDialog.value.visible = true
      Object.assign(folderForm, {
        name: '',
        description: ''
      })
    }

    const createFolderConfirm = async () => {
      try {
        creatingFolder.value = true
        
        // 模拟创建文件夹
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('文件夹创建成功')
        folderDialog.value.visible = false
      } catch (error) {
        ElMessage.error('创建失败：' + error.message)
      } finally {
        creatingFolder.value = false
      }
    }

    const batchDownload = () => {
      ElMessage.info(`开始批量下载 ${selectedFiles.value.length} 个文件`)
      selectedFiles.value = []
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
          '确认批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const selectedIds = selectedFiles.value.map(f => f.id)
        files.value = files.value.filter(f => !selectedIds.includes(f.id))
        
        ElMessage.success('批量删除成功')
        selectedFiles.value = []
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败：' + error.message)
        }
      }
    }

    const batchMove = () => {
      ElMessage.info(`批量移动 ${selectedFiles.value.length} 个文件`)
      selectedFiles.value = []
    }

    const navigateToPath = (index) => {
      currentPath.value = currentPath.value.slice(0, index + 1)
    }

    const selectFile = (file) => {
      console.log('Select file:', file)
    }

    const openFile = (file) => {
      if (file.type === 'folder') {
        // 进入文件夹
        currentPath.value.push({ name: file.name, path: file.path })
      } else {
        // 预览文件
        showPreviewFile(file)
      }
    }

    // 工具方法
    const getFileIcon = (type) => {
      // 在Options API中，图标已在components中注册，字符串引用有效
      const iconMap = {
        image: 'Picture',
        document: 'Document',
        video: 'VideoPlay',
        audio: 'Headset',
        archive: 'Box',
        folder: 'Folder',
        other: 'Document'
      }
      return iconMap[type] || 'Document'
    }

    const getFileIconClass = (type) => {
      const classMap = {
        image: 'file-icon-image',
        document: 'file-icon-document',
        video: 'file-icon-video',
        audio: 'file-icon-audio',
        archive: 'file-icon-archive',
        folder: 'file-icon-folder',
        other: 'file-icon-other'
      }
      return classMap[type] || 'file-icon-other'
    }

    const getTypeTagType = (type) => {
      const typeMap = {
        image: 'success',
        document: 'primary',
        video: 'warning',
        audio: 'info',
        archive: 'danger',
        other: 'info'
      }
      return typeMap[type] || 'info'
    }

    const translateFileType = (type) => {
      const typeMap = {
        image: '图片',
        document: '文档',
        video: '视频',
        audio: '音频',
        archive: '压缩包',
        folder: '文件夹',
        other: '其他'
      }
      return typeMap[type] || '其他'
    }

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN')
    }

    const formatDate = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleDateString('zh-CN')
    }

    const isImage = (type) => type === 'image'
    const isDocument = (type) => type === 'document'
    const isVideo = (type) => type === 'video'
    const isAudio = (type) => type === 'audio'

    // 生命周期
    onMounted(async () => {
      loading.value = true
      try {
        await refreshFiles()
      } catch (error) {
        console.error('Failed to load files:', error)
      } finally {
        loading.value = false
      }
    })

    return {
      loading,
      searchKeyword,
      typeFilter,
      sizeFilter,
      dateRange,
      viewMode,
      currentPage,
      pageSize,
      selectedFiles,
      uploading,
      creatingFolder,
      uploadDialog,
      previewDialog,
      folderDialog,
      folderForm,
      folderRules,
      previewFile,
      fileList,
      files,
      currentPath,
      stats,
      filteredFiles,
      paginatedFiles,
      uploadAction,
      uploadHeaders,
      uploadData,
      refreshFiles,
      handleSearch,
      handleFilter,
      resetFilters,
      applyFilters,
      handleSelectionChange,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      showUploadDialog,
      handleFileChange,
      handleUploadSuccess,
      handleUploadError,
      startUpload,
      showPreviewFile,
      downloadFile,
      deleteFile,
      createFolder,
      createFolderConfirm,
      batchDownload,
      batchDelete,
      batchMove,
      navigateToPath,
      selectFile,
      openFile,
      getFileIcon,
      getFileIconClass,
      getTypeTagType,
      translateFileType,
      formatFileSize,
      formatDateTime,
      formatDate,
      isImage,
      isDocument,
      isVideo,
      isAudio,
      authStore,
      PERMISSIONS
    }
  }
}
</script>

<style scoped>
.file-management-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.size { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.today { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.folders { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.path-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.file-path {
  padding: 8px 0;
}

.path-item {
  cursor: pointer;
  transition: color 0.3s;
}

.path-item:hover {
  color: #409eff;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  display: flex;
  align-items: center;
}

.file-list-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  font-size: 16px;
}

.file-icon-image { color: #67c23a; }
.file-icon-document { color: #409eff; }
.file-icon-video { color: #e6a23c; }
.file-icon-audio { color: #f56c6c; }
.file-icon-archive { color: #909399; }
.file-icon-folder { color: #e6a23c; }
.file-icon-other { color: #909399; }

.grid-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.file-card {
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 16px;
  background: white;
  transition: all 0.3s ease;
  cursor: pointer;
}

.file-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.file-icon-large {
  text-align: center;
  margin-bottom: 12px;
  font-size: 48px;
}

.file-info {
  text-align: center;
  margin-bottom: 12px;
}

.file-info .file-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions-card {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  font-weight: 500;
  color: #303133;
}

.upload-dragger {
  width: 100%;
}

.upload-list {
  margin-top: 20px;
}

.upload-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 8px;
}

.upload-item .file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-progress {
  width: 200px;
}

.file-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 600px;
  border-radius: 8px;
}

.document-preview iframe {
  border-radius: 8px;
}

.video-preview video {
  border-radius: 8px;
}

.audio-preview audio {
  border-radius: 8px;
}

.other-preview {
  padding: 40px;
}

.preview-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.preview-info h3 {
  margin: 0 0 16px 0;
  color: #303133;
}

.preview-info p {
  margin: 8px 0;
  color: #606266;
}

.preview-actions {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .file-management-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-toolbar {
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-left {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .grid-view {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

